import json

from flask import request, abort, Blueprint

from models import Book, BookClassify

book = Blueprint('book', __name__)


@book.route('/bookClassify/')
def book_classify():
    try:
        data = dict(
            code=200,
            msg='请求成功!',
            data=[]
        )
        items = BookClassify.query.all()
        for item in items:
            data['data'].append({
                'id': item.id,
                'name': item.classifyName
            })
        return json.dumps(data)
    except Exception as e:
        abort(500)


@book.route('/book/<int:id>/')
def get_book(id):
    args = request.args
    if args and id:
        page = args.get('page', type=int, default=1)
        count = args.get('count', type=int, default=10)
        if isinstance(page, int) and isinstance(count, int):
            data = {'code': 200, 'msg': '请求成功!', 'data': []}
            page = (page - 1) * count
            count = page + count
            books = Book.query.filer(
                Book.classifyID == id
            ).limit(page).offset(count).getall()
            for book in books:
                data['data'].append(
                    dict(
                        title=book.title,
                        author=book.author,
                        synopsis=book.synopsis,
                        id=book.bookGuid,
                        img=book.img,
                        chapterCount=book.chapterCount
                    )
                )
        else:
            abort(403)
    else:
        abort(403)
